(function(){
	if(!window.cell) window.cell={};
	if(!window.cell.bookmark) window.cell.bookmark={};
	if(!window.$b) window.$b = cell.bookmark = function(uri) {
		if ( window == this || !this.init ){
			return new cell.bookmark(uri);
		}
		return this.init(uri);
	}
	cell.bookmark.fn = cell.bookmark.prototype = {
		version: "2.0.2",
		bmsvc: Components.classes["@mozilla.org/browser/nav-bookmarks-service;1"].getService(Components.interfaces.nsINavBookmarksService),
		favisvc: Components.classes["@mozilla.org/browser/favicon-service;1"].getService(Components.interfaces.nsIFaviconService),
		init: function(uri) {
			try{
				this.uri=Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService).newURI(uri, null, null);
				//return this.uri
			}catch(err){
				return false;
			}
		},
		has:function (){
			if(!this.bmsvc.isBookmarked(this.uri)){
				return false;
			}else{
				return true;
			}
		},
		favicon:function (){
			try{
				return this.favisvc.getFaviconForPage(this.uri).spec;
			}catch(err){
				return this.favisvc.defaultFavicon.spec;
			}
		},
		get:function(){
			return this.bmsvc.getBookmarkIdsForURI(this.uri,{});
		},
		add:function(arg){
			if(this.has()){return false;}
			if(!arg) var arg={}
			if(!arg.title){arg.titel=null}
			return this.bmsvc.insertBookmark(this.bmsvc.unfiledBookmarksFolder,this.uri,-1,arg.title);
		},
		remove:function(){
			if(!this.has()){return false;}
			this.bmsvc.removeItem(this.get());
			return true;
		},
		thumbnail:function(arg){
			var hidden = Components.classes["@mozilla.org/appshell/appShellService;1"].getService(Components.interfaces.nsIAppShellService).hiddenDOMWindow.document;
			var iframe = hidden.createElementNS("http://www.w3.org/1999/xhtml","iframe");
			iframe.width='100%'
			iframe.height='100%'
			var canvas = document.createElementNS("http://www.w3.org/1999/xhtml","canvas");
			
			iframe.addEventListener("load", function(arg){
				
				if(!arg) var arg={};
				if(!arg.background) arg.background="rgb(255,255,255)";
				if(!arg.width) arg.width= (window.screen.width/6);
				if(!arg.height) arg.height= (window.screen.height/6);

				canvas.width = arg.width;
				canvas.height = arg.height;
				
				var width=this.contentDocument.documentElement.scrollWidth;
				var scale=canvas.width / width;
				var height=canvas.height / scale;
				
				var ctx = canvas.getContext("2d");
				ctx.clearRect(0, 0, canvas.width, canvas.height);
				ctx.save();
				ctx.scale(scale,scale);
				ctx.drawWindow(this.contentWindow, 0, 0, this.contentDocument.documentElement.scrollWidth, this.contentDocument.documentElement.scrollHeight, arg.background);
				ctx.restore();
				
				var parent=this.parentNode;
				parent.removeChild(this);
			}, true);
			iframe.setAttribute("src", this.uri.asciiSpec);
			hidden.documentElement.appendChild(iframe);
			return canvas;
		},
		
	}
})();
